<template>
  <view class="edit">
    <nut-form ref="formRef" :rules="rules" v-model="formData">
      <nut-form-item label="商品名称" prop="goodsName" required label-position="top" star-position="right">
        <nut-textarea
          textarea-style="font-size:40rpx;font-weight: bold;"
          required
          textarea-class="ntextarea"
          v-model="formData.goodsName"
          :autosize="{ maxHeight: 60, minHeight: 60 }"
          placeholder="请输入 商品名称"
        />
      </nut-form-item>

      <nut-form-item label="生产日期" prop="productionDate" required star-position="right">
        <picker mode="date" :value="formData.productionDate" @change="bindTimeChange($event, 'productionDate')">
          <nut-input readonly v-model="formData.productionDate" placeholder="请选择 生产日期" type="text" />
        </picker>
      </nut-form-item>

      <nut-form-item label="保质期" prop="shelfLife" required star-position="right">
        <picker mode="date" :value="formData.shelfLife" @change="bindTimeChange($event, 'shelfLife')">
          <nut-input readonly v-model="formData.shelfLife" placeholder="请选择 保质期" type="text" />
        </picker>
      </nut-form-item>

      <nut-form-item label="数量" prop="number" required star-position="right">
        <nut-input-number v-model="formData.number" />
      </nut-form-item>

      <nut-form-item label="价格" prop="price">
        <nut-input v-model="formData.price" type="digit" placeholder="请输入 价格" />
      </nut-form-item>

      <nut-form-item label="品牌" prop="brand">
        <nut-input v-model="formData.brand" placeholder="请输入 品牌" type="text" />
      </nut-form-item>

      <nut-form-item label="厂商" prop="supplier">
        <nut-input v-model="formData.supplier" placeholder="请输入 厂商" type="text" />
      </nut-form-item>

      <nut-form-item label="位置" prop="location">
        <nut-input v-model="formData.location" placeholder="请输入 位置" type="text" />
      </nut-form-item>

      <nut-form-item label="条形码" prop="code">
        <nut-input v-model="formData.code" type="text" />
      </nut-form-item>

      <nut-form-item label="保质期前15天提醒" label-width="250rpx">
        <nut-button @click="onSubscribe" :type="formData.subscriptionFlag ? 'info' : 'warning'" size="mini" :color="formData.subscriptionFlag ? '' : '#8b8b8b'">
          {{ formData.subscriptionFlag ? "已订阅" : "未订阅" }}
        </nut-button>
      </nut-form-item>

      <nut-form-item v-if="formData.goodsName && formData.shelfLife" label="添加到系统日历提醒" label-width="250rpx">
        <nut-button @click="onSubscribe2" type="info" size="mini">添加</nut-button>
      </nut-form-item>
      <div class="btns">
        <nut-button size="large" type="info" @click="submit">提交</nut-button>
      </div>
    </nut-form>
  </view>
</template>

<script setup>
import { ref } from "vue";
import { getScan } from "../../api/sacn";
import { addStore, oneStore, updateStore, deleteStore } from "../../api/store";
import { onBack } from "../../hooks/useRoute";
import useCalendar from "../../hooks/useCalendar";
import { onLoad } from "@dcloudio/uni-app";
import dayjs from "dayjs";

const form = ref({});

const formData = ref({
  goodsName: "",
  shelfLife: "",
  productionDate: "",
  number: 1,
  supplier: "",
  brand: "",
  code: "",
  subscriptionFlag: 0,
});

const formRef = ref(null);

const rules = {
  goodsName: [{ required: true, message: "请填写商品名称" }],
  shelfLife: [{ required: true, message: "请选择保质期" }],
  productionDate: [{ required: true, message: "请选择生产日期" }],
  number: [{ required: true, message: "请填写数量" }],
};

onLoad((options) => {
  form.value = options;
  if (form.value.id) {
    getOneStore();
  } else if (form.value.code) {
    formData.value.code = form.value.code;

    getData();
  }
});

function getData() {
  const { code } = form.value;
  getScan({ code }).then(({ data }) => {
    formData.value = { ...formData.value, ...data };
  });
}

function bindTimeChange({ detail: { value } }, key) {
  formData.value[key] = value;
}

// function onDelate() {
//   useModal({
//     title: "确认删除？",
//     success: ({ confirm }) => {
//       if (confirm) {
//         const { id } = form.value;
//         deleteStore({ id }).then(() => {
//           onBack();
//         });
//       }
//     },
//   });
// }

function getOneStore() {
  const { id } = form.value;
  oneStore({ id }).then(({ data }) => {
    formData.value = data;
  });
}

function submit() {
  const { id, code } = form.value;
  formRef.value?.validate().then(({ valid }) => {
    if (valid) {
      if (id) {
        updateStore({ ...formData.value, id }).then(() => {
          onBack();
        });
        return;
      }

      addStore({ ...formData.value, code }).then(() => {
        onBack();
      });
    }
  });
}

function onSubscribe() {
  if (formData.value.subscriptionFlag === 1) {
    formData.value.subscriptionFlag = 0;
    return;
  }

  wx.requestSubscribeMessage({
    tmplIds: ["Cn5mkp-NjnrSwWkL5QN5cKFjX2KTalaar8S1njj-D98"],
    success(res) {
      if (res["Cn5mkp-NjnrSwWkL5QN5cKFjX2KTalaar8S1njj-D98"] === "accept") {
        formData.value.subscriptionFlag = 1;
        return;
      }
    },
  });
}

function onSubscribe2() {
  const { shelfLife, goodsName } = formData.value;
  useCalendar({
    startTime: new Date(dayjs(shelfLife).subtract(15, "day").format("YYYY/MM/DD 08:00")).getTime() / 1000,
    title: "物品过期提醒",
    description: `您的 ${goodsName} 将在15天后过期，请留意！`,
  });
}
</script>

<style lang="scss">
.edit {
  padding: 0 20rpx;
}

.ntextarea {
  font-size: 42rpx;
}

.edit-text {
  font-size: 32rpx;
}

.btns {
  margin: 60rpx 40rpx;
}
</style>
